package nsqp

import (
	"bgs/cache/redisImp"
	"bgs/conf"
	"bgs/db"
	"bgs/grpc/client"
	"bgs/grpc/imp/enums"
	handlers "bgs/nsqp/handlers/inventory"
	"bgs/nsqp/topic"
	"bgs/nsqp/util"
	enforcementService "bgs/service/enforcement"
	ledgerService "bgs/service/ledger"
	wxpMinaService "bgs/wxp/mina"
	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

// const (
// 	topicOfWarehouseUpsert    = "update"
// 	topicOfProcessOrderUpdate = "order_update"
// )

// func makeInventoryTopic(topic string) string {
// 	return fmt.Sprintf("%s-%s", enums.APPIDINVENTORY, topic)
// }

// InventoryProxy proxy inventory nsq message
type InventoryProxy struct {
	slog *zap.SugaredLogger
	subs []*nsq.Consumer
}

// NewInventoryProxy initialization
func NewInventoryProxy(
	nsqConf conf.NsqSection,
	pgdao *db.PgDao,
	slog *zap.SugaredLogger,
	vars *conf.VarsSection,
	clientProxy *client.GrpcClientProxy,
	adp *cache.Adapter,
	failover *util.NsqFailover,
	enforcementService *enforcementService.EnforcementServiceImp,
	ledgerService *ledgerService.LedgerServiceImp,
	wxpMinaService *wxpMinaService.MinaServiceImp,
) (proxy *InventoryProxy, err error) {
	proxy = &InventoryProxy{
		slog: slog.With("module", "InventoryProxy"),
	}

	config := nsq.NewConfig()

	// warehouseUpsertConsumer
	warehouseUpsertConsumerTopic := topic.Make(enums.APPIDINVENTORY)(topic.WarehouseUpsert)
	warehouseUpsertConsumer, err := nsq.NewConsumer(warehouseUpsertConsumerTopic, appID, config)
	if err != nil {
		return
	}
	warehouseUpsertConsumer.SetLogger(
		nsqLogger,
		nsq.LogLevelError,
	)
	warehouseUpsertConsumer.AddHandler(handlers.NewWarehouseUpsertHandler(pgdao, proxy.slog, warehouseUpsertConsumerTopic, failover))
	err = warehouseUpsertConsumer.ConnectToNSQLookupd(nsqConf.NsqLookupds[0])
	if err != nil {
		return
	}
	proxy.subs = append(proxy.subs, warehouseUpsertConsumer)

	// processOrderUpdateConsumer
	processOrderUpdateConsumerTopic := topic.Make(enums.APPIDINVENTORY)(topic.OrderUpdate)
	processOrderUpdateConsumer, err := nsq.NewConsumer(processOrderUpdateConsumerTopic, appID, config)
	if err != nil {
		return
	}
	processOrderUpdateConsumer.SetLogger(
		nsqLogger,
		nsq.LogLevelError,
	)
	processOrderUpdateConsumer.AddHandler(handlers.NewProcessOrderUpdateHandler(pgdao, proxy.slog, processOrderUpdateConsumerTopic, failover,
		enforcementService, ledgerService, wxpMinaService))
	err = processOrderUpdateConsumer.ConnectToNSQLookupd(nsqConf.NsqLookupds[0])
	if err != nil {
		return
	}
	proxy.subs = append(proxy.subs, processOrderUpdateConsumer)

	// Gracefully stop the consumer.
	// consumer.Stop()

	return
}
